package com.goodedeeds.webapp;

import com.goodedeeds.webapp.controller.LoginAction;
import com.youtills.core.auth.IAuth;
import com.youtills.core.auth.IAuthUser;
import com.youtills.core.config.Configuration;
import com.youtills.core.config.IConfig;
import com.youtills.core.lang.StringUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: rchiluve
 * Date: 1/28/14
 * Time: 8:55 PM
 * To change this template use File | Settings | File Templates.
 */
public class SecurityFilter implements Filter {

    private final Date TEMP_DATE = new Date(1348685362746L); //2012-09-26 @11:49AM
    private IConfig config = Configuration.getConfig("quiggle.is.live");

    /* (non-Javadoc)
      * @see javax.servlet.Filter#destroy()
      */
    public void destroy() {
    }

    /* (non-Javadoc)
      * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
      */
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {

        try{
            if(!(req instanceof HttpServletRequest) || !(res instanceof HttpServletResponse)){
                chain.doFilter(req, res);
                return;
            }

            final HttpServletRequest request = (HttpServletRequest) req;
            final HttpServletResponse response = (HttpServletResponse) res;

//            javax.servlet.D 

            String resource = request.getServletPath();

            if(isPublicResource(resource)){
                chain.doFilter(request, response);
                return;
            }

            checkAuthentication(request, response, chain);
        }catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    /* (non-Javadoc)
      * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
      */
    public void init(FilterConfig arg0) throws ServletException {

    }

    private static final List<String> PUBLIC_RESOURCES = Arrays.asList(
            LoginAction.URL
    );

    private boolean isPublicResource(String resource){
//		System.out.println("Ispublic Resource : " + resource);
//        return PUBLIC_RESOURCES.contains(resource);
        return true;
    }

    private void checkAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException{

        try{
            IAuth auth = LoginHandler.getInstance().fetchAuth(req, res);

            if(auth != null){
                req.setAttribute(LoginHandler.AUTH_KEY, auth);

                IAuthUser user = auth.getAuthUser();

                boolean isLive = StringUtil.getBoolean(config.getStringValue(), false);

//                if(!isLive && (user.getCreatedDate() == null || TEMP_DATE.before(user.getCreatedDate()))){
//                    redirect(ThankYouAction.URL, req, res, chain);
//                    return;
//                }

                if(user.isTempPassword()){
                    //redirect change password.
//                    redirect(ChangePasswordAction.URL, req, res, chain);
                    return;
                }
                if(user.isLocked()){
//                    redirect(UserLockedAction.URL, req, res, chain);
                    return;
                }

                chain.doFilter(req, res);
                return;
            }else{
                redirect(LoginAction.URL, req, res, chain);
                return;
            }
        }catch (Exception e) {
            redirect(LoginAction.URL, req, res, chain);
            return;
        }
    }

    private void redirect(String target, HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        try{
            String resource = request.getServletPath();

            if(target.equals(resource)){
                chain.doFilter(request, response);
                return;
            }

            if(target.startsWith("/")){
                target = target.substring(1);
            }

            response.sendRedirect(target);
            return;
        }catch (Exception e) {
            return;
        }
    }


    public static void main(String[] args){
        System.out.print(System.currentTimeMillis());
    }
}
